package com.goods.redis2msyql;

import com.goods.redis2msyql.service.MysqlService;
import com.goods.redis2msyql.service.RedisService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author Dan
 * Created by Administrator on 2015/5/21.
 */
public class Main {
    public static void main(String[] args){
        RedisService redisService = new RedisService();
        MysqlService mysqlService = new MysqlService();
        new Main().executeFixedDelay(redisService,mysqlService);
    }

    public void executeFixedDelay(RedisService redisService,MysqlService mysqlService){
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        executor.scheduleWithFixedDelay(
                new EchoServer(redisService,mysqlService),
                0,
                10,
                TimeUnit.SECONDS);
    }

    private class EchoServer implements Runnable{
        private RedisService redisService;
        private MysqlService mysqlService;

        private EchoServer(RedisService redisService,MysqlService mysqlService) {
            this.mysqlService = mysqlService;
            this.redisService = redisService;
        }

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()){
                String s = redisService.popNeedPush();
                if(s==null){
                    break;
                }

                String value = redisService.getKey(s);
                mysqlService.saveOrUpdate(s,value);
            }
        }
    }
}
